//
//  UIFont+Ex.swift
//  
//
//  Created by tank on 2021/12/16.
//

import Foundation
import LibBase
import UIKit

extension Extension where Base == UIFont {
    public static func iconFont(ofSize size: CGFloat) -> UIFont {
        return IconFonts.shared.iconFont(size: size)
    }
    
    public static func registerFont(forResource: String, identifier: String) -> Bool {
        guard let bundle = Bundle(identifier: identifier) else {
            return false
        }
        
        return registerFont(forResource: forResource, bundle: bundle)
    }
    
    public static func registerFont(forResource: String, bundle: Bundle) -> Bool {
        guard let path = bundle.path(forResource: forResource, ofType: nil) else {
            return false
        }
        
        guard let fontData = NSData(contentsOfFile: path) else {
            return false
        }
        
        guard let dataProvider = CGDataProvider(data: fontData) else {
            return false
        }
        
        var errorRef: Unmanaged<CFError>?
        if !CTFontManagerRegisterGraphicsFont(CGFont(dataProvider)!, &errorRef) {
            return false
        }
        
        return true
    }
    
    public static func font(names: [String], size: CGFloat) -> UIFont {
        guard let mainFontName = names.first else {
            return UIFont.systemFont(ofSize: size)
        }
        
        let descriptors = names.map { UIFontDescriptor(fontAttributes: [.name: $0]) }
        
        let attributes: [UIFontDescriptor.AttributeName: Any] = [
            UIFontDescriptor.AttributeName.cascadeList: descriptors,
            UIFontDescriptor.AttributeName.name: mainFontName,
            UIFontDescriptor.AttributeName.size: size,
        ]
        
        let customFontDescriptor: UIFontDescriptor = UIFontDescriptor(fontAttributes: attributes)
        return UIFont(descriptor: customFontDescriptor, size: size)
    }
    
    public static func font(families: [String], size: CGFloat, weight: UIFont.Weight = .regular) -> UIFont {
        guard let mainFontFamily = families.first else {
            return UIFont.systemFont(ofSize: size, weight: weight)
        }
        
        let descriptors = families.map { UIFontDescriptor(fontAttributes: [.family: $0]) }
        let traits = [UIFontDescriptor.TraitKey.weight: weight]
        
        let attributes: [UIFontDescriptor.AttributeName: Any] = [
            UIFontDescriptor.AttributeName.cascadeList: descriptors,
            UIFontDescriptor.AttributeName.family: mainFontFamily,
            UIFontDescriptor.AttributeName.size: size,
            UIFontDescriptor.AttributeName.traits: traits
        ]
        
        let customFontDescriptor: UIFontDescriptor = UIFontDescriptor(fontAttributes: attributes)
        return UIFont(descriptor: customFontDescriptor, size: size)
    }
}
